﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Stock.Models.Classes;
using NHibernate.Criterion;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using Stock.Properties;


namespace Stock
{
    public partial class Form1 : Form
    {
        private BindingSource Source;   // This is the collection that contains products and it is the DataSource in the DataGridView
        private bool NewRowsUnsaved;    // If a new row was added and no saved, this attribute will be true.
        private bool RowsEdited;        // If some cell was edited, this attribute will be true.

        public Form1()
        {
            InitializeComponent();
            
            Source = new BindingSource();

            Repository repository = Repository.Instance;
            List<Product> products = (List<Product>)repository.Session.CreateCriteria<Product>().List<Product>();
            LoadProducts(products);
            ConfigureDataGrid();
            //Console.WriteLine(Settings.Default["multiplicador"]);
            //Settings.Default["multiplicador"] = 1;
            //Settings.Default.Save();
            NameTxt.Text = null;
            QuantityNum.Value = 0;
            CostPriceTxt.Text = "0";
            ListPriceTxt.Text = "0";
            ImageBox.ImageLocation = "";
            NewRowsUnsaved = false;
            RowsEdited = false;
        }

        public static byte[] ConversionImagen(string nombrearchivo)
        {
            //Declaramos fs para poder abrir la imagen.
            FileStream fs = new FileStream(nombrearchivo, FileMode.Open);

            // Declaramos un lector binario para pasar la imagen
            // a bytes
            BinaryReader br = new BinaryReader(fs);
            byte[] imagen = new byte[(int)fs.Length];
            br.Read(imagen, 0, (int)fs.Length);
            br.Close();
            fs.Close();
            return imagen;
        }

        public Image ConversionByte(byte[] imageBytes)
        {
            // Convierte byte[] a Imagen
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = new Bitmap(ms);
            return image;
        }

        /* Setting parameters to the columns */
        private void ConfigureDataGrid()
        {
            ProductsDataGrid.Columns["Id"].Visible = false;
            //ProductsDataGrid.Columns["Image"].Visible = false;
            ProductsDataGrid.Columns["Name"].HeaderText = "Nombre";
            ProductsDataGrid.Columns["Quantity"].HeaderText = "Cantidad";
            ProductsDataGrid.Columns["CostPrice"].HeaderText = "Precio Costo";
            ProductsDataGrid.Columns["ListPrice"].HeaderText = "Precio Lista";
            ProductsDataGrid.Columns["Name"].DisplayIndex = 1;
            ProductsDataGrid.Columns["Quantity"].DisplayIndex = 2;
            ProductsDataGrid.Columns["CostPrice"].DisplayIndex = 3;
            ProductsDataGrid.Columns["ListPrice"].DisplayIndex = 4;

        }

        /* Loading products to the DataGridView */
        private void LoadProducts(List<Product> products)
        {
            Source.DataSource = products;
            ProductsDataGrid.DataSource = Source;
        }

        private void SearchTxt_TextChanged(object sender, EventArgs e)
        {
            /* Finding all products by name */
            var products = Repository.Instance.Session.CreateCriteria<Product>()
                                                                        .Add(Restrictions.Like("Name", "%" + searchTxt.Text + "%")).List<Product>();
            LoadProducts(products.ToList<Product>());
         }
        
        /* Adding a new product to the DataGridView */
        private void addProductBtn_Click(object sender, EventArgs e)
        {
            Source.Add(new Product());
        }

        private void SaveAll()
        {
            Repository repository = Repository.Instance;
            repository.SaveAll<Product>((List<Product>)Source.DataSource);
            //notificacionLbl.Visible = false;
            NewRowsUnsaved = false;
        }

        private void guardarBtn_Click(object sender, EventArgs e)
        {
            Repository repository = Repository.Instance;
            Product pro = new Product();
            pro.Name = NameTxt.Text;
            pro.Quantity = QuantityNum.Value;
            pro.CostPrice = decimal.Parse(Herramientas.PuntoToComa(CostPriceTxt.Text));
            pro.ListPrice = decimal.Parse(Herramientas.PuntoToComa(ListPriceTxt.Text));            
            repository.Save<Product>(pro);
            Source.Add(pro);
            List<Product> products = (List<Product>)repository.Session.CreateCriteria<Product>().List<Product>();            
            if (ImageBox.ImageLocation != "")
            {
                GuardarImagen(ImageBox.ImageLocation, products.Last<Product>());
            }
            NameTxt.Text = null;
            QuantityNum.Value = 0;
            CostPriceTxt.Text = "0";
            ListPriceTxt.Text = "0";
          
        }

        private void RemoveProductBtn_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("¿Está seguro que desea eliminar este producto?",
                                            "Eliminar producto", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                Repository repository = Repository.Instance;
                Product product = (Product)Source.Current;
                Source.Remove(product);
                repository.Session.Delete(product);
                repository.Session.Flush();
                NameTxt.Text = null;
                QuantityNum.Value = 0;
                CostPriceTxt.Text = "0";
                ListPriceTxt.Text = "0";
                ModBtn.Visible = false;
                guardarBtn.Visible = true;
            }
        }

        private void ProductsDataGrid_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            NewRowsUnsaved = true;
           // notificacionLbl.Visible = true;
        }

        private void searchTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
           /* if (NewRowsUnsaved)
            {
                DialogResult dialogResult = MessageBox.Show("Se deben guardar los nuevos productos agregados o se perderán ¿Desea guardarlos?",
                                                            "Datos sin guardar", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes) 
                    SaveAll();
                else
                {
                    NewRowsUnsaved = false;
                    notificacionLbl.Visible = (NewRowsUnsaved || RowsEdited);
                }
            }*/
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ProductsDataGrid.CellValueChanged += new DataGridViewCellEventHandler(
            ProductsDataGrid_CellValueChanged);
        }

        private void ProductsDataGrid_CellValueChanged(
        object sender, DataGridViewCellEventArgs e)
        {
            if(!RowsEdited) RowsEdited = true;
            //notificacionLbl.Visible = true;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (NewRowsUnsaved || RowsEdited)
            {
                DialogResult answer = MessageBox.Show("¿Desea guardar los cambios antes de cerrar?", "Datos sin guardar", MessageBoxButtons.YesNoCancel);
                switch (answer)
                {
                    case  DialogResult.Yes:
                        SaveAll();
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }

        private void logo_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.flexitargentina.com.ar");
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void configurarMultiplicadorTsm_Click(object sender, EventArgs e)
        {

        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void congafsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NameTxt.Text = null;
            QuantityNum.Value = 0;
            CostPriceTxt.Text = "0";
            ListPriceTxt.Text = "0";
            ModBtn.Visible = false;
            guardarBtn.Visible = true;
            Form2 frm = new Form2();
            frm.ShowDialog();
            Source.ResetBindings(true);
        }

        private void ImageBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|JPEG Files (*.jpeg)|*.jpeg|GIF Files (*.gif)|*.gif";
            DialogResult Dialog = dlg.ShowDialog();

            if (Dialog == DialogResult.OK)
            {

                ImageBox.ImageLocation = dlg.FileName;
            }
        }

        private void NameTxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void ProductsDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Repository repository = Repository.Instance;
            Product product = (Product)Source.Current;
            NameTxt.Text = product.Name;
            QuantityNum.Value = product.Quantity;
            CostPriceTxt.Text = Convert.ToString (product.CostPrice);
            ListPriceTxt.Text = Convert.ToString(product.ListPrice);
            ModBtn.Visible = true;
            guardarBtn.Visible = false;
            if (System.IO.File.Exists(Application.StartupPath + ("\\Imagenes") + ("\\") + product.Id + (".jpg")))
            {
                ImageBox.ImageLocation = Application.StartupPath + ("\\Imagenes") + ("\\") + product.Id + (".jpg");
            }
            else
            {
                ImageBox.ImageLocation = "";
            }
           // List<Product> products = (List<Product>)repository.Session.CreateCriteria<Product>().List<Product>();
           // LoadProducts(products);
           // ConfigureDataGrid();
        }

        private void ModBtn_Click(object sender, EventArgs e)
        {
            Repository repository = Repository.Instance;
            Product product = (Product)Source.Current;
            product.Name = NameTxt.Text;
            product.Quantity = QuantityNum.Value;
            product.CostPrice = decimal.Parse(Herramientas.PuntoToComa(CostPriceTxt.Text));
            product.ListPrice = decimal.Parse(Herramientas.PuntoToComa(ListPriceTxt.Text));
            repository.Save(product);
            if (ImageBox.ImageLocation != "")
            {
                if (String.Compare(Application.StartupPath + ("\\Imagenes") + ("\\") + product.Id + (".jpg"), ImageBox.ImageLocation) != 0)
                {
                    GuardarImagen(ImageBox.ImageLocation, product);
                }
            }     
            ModBtn.Visible = false;
            NameTxt.Text = null;
            QuantityNum.Value = 0;
            CostPriceTxt.Text = "0";
            ListPriceTxt.Text = "0";
            ImageBox.ImageLocation = "";
            guardarBtn.Visible = true;
            List<Product> products = (List<Product>)repository.Session.CreateCriteria<Product>().List<Product>();
            LoadProducts(products);
            ConfigureDataGrid();

        }

        private void clicpantalla(object sender, MouseEventArgs e)
        {
            NameTxt.Text = null;
            QuantityNum.Value = 0;
            CostPriceTxt.Text = "0";
            ListPriceTxt.Text = "0";
            ModBtn.Visible = false;
            guardarBtn.Visible = true;
            ImageBox.ImageLocation = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            decimal multiplicador = (decimal)Settings.Default["multiplicador"];
            ListPriceTxt.Text = Convert.ToString(decimal.Parse(Herramientas.PuntoToComa(CostPriceTxt.Text)) + decimal.Parse(Herramientas.PuntoToComa(CostPriceTxt.Text)) * (multiplicador / 100));
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            clicpantalla(null, null);
        }

        private void GuardarImagen (string DirectorioEntrada,Product pro)
        {
            System.IO.File.Copy(DirectorioEntrada, Application.StartupPath + ("\\Imagenes") + ("\\") + pro.Id + (".jpg"), true);
        }

        private void AgrandarImagen(object sender, EventArgs e)
        {
            Repository repository = Repository.Instance;
            Product pro = (Product)Source.Current;
            string loc = Application.StartupPath + ("\\Imagenes") + ("\\") + pro.Id + (".jpg");
            Form3 frm = new Form3(loc);
            frm.ShowDialog();
        }

        private void ProductsDataGrid_KeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void ProductsDataGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
               
                ProductsDataGrid_CellContentClick(null, null);
                e.SuppressKeyPress = true;
            }
        }

        private void Form1_Load_1(object sender, EventArgs e)
        {
            this.AllowDrop = true;

            // Add event handlers for the drag & drop functionality
            this.DragEnter += new DragEventHandler(Form1_DragEnter);
            this.DragDrop += new DragEventHandler(Form1_DragDrop);
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            // Check if the Dataformat of the data can be accepted
            // (we only accept file drops from Explorer, etc.)
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy; // Okay
            else
                e.Effect = DragDropEffects.None; // Unknown data, ignore it
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            // Extract the data from the DataObject-Container into a string list
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

            // Do something with the data...

            // For example add all files into a simple label control:
            foreach (string File in FileList)
                ImageBox.ImageLocation = File;
        }

       

        

  }
}

